package io.renren.common.exception;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import io.renren.common.vo.RV;



/**
 * 全局异常处理
 * @author tang
 *
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/**
	 * 基本异常处理
	 * @param response
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(BaseException.class)
    public RV baseExceptionHandler(HttpServletResponse response, BaseException ex) {
		//response.setStatus(500);
		logger.error(ex.getMessage(),ex);
        return RV.fail(ex.getCode(),ex.getMessage());
    }

	/**
	 * 业务异常处理
	 * @param response
	 * @param ex
     * @return
     */
	@ExceptionHandler(BizException.class)
	public RV bizExceptionHandler(HttpServletResponse response, BizException ex) {
		//response.setStatus(500);
		logger.error(ex.getMessage(),ex);
		return RV.fail(ex.getCode(),ex.getMessage());
	}
	
	@ExceptionHandler(NoHandlerFoundException.class)
	public RV handlerNoFoundException(Exception e) {
		logger.error(e.getMessage(), e);
		return RV.fail("404", "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public RV handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return RV.fail("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public RV handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
		return RV.fail("没有权限，请联系管理员授权");
	}

	/**
	 * 其他异常处理
	 * @param response
	 * @param ex
	 * @return
	 */
    @ExceptionHandler(Exception.class)
    public RV otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        logger.error(ex.getMessage(),ex);
    	return RV.fail(response.getStatus()+"",ex.getMessage());
    }

   
}
